from django.apps import AppConfig
import os
import signal
import threading
import sys

class App01Config(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "app01"

    # 标志位避免重复启动
    _service_started = False
    _lock = threading.Lock()

    def ready(self):
        # 仅在主进程启动一次服务（排除自动重载进程）
        if os.environ.get('RUN_MAIN') == 'true':
            with self._lock:
                if not self._service_started:
                    from .services.service_manager import service_manager
                    service_manager.start_all()
                    self._service_started = True

                    # 注册优雅退出
                    signal.signal(signal.SIGINT, self._shutdown)
                    signal.signal(signal.SIGTERM, self._shutdown)

    def _shutdown(self, signum, frame):
        from .services.service_manager import service_manager
        service_manager.stop_all()
        sys.exit(0)